package top.ajax;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import top.mapper.UserMapper;
import top.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 *   AJAX案例
 *
 */
@WebServlet("/ajax2")
public class AjaxTest extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                                                throws ServletException, IOException {
        String username = req.getParameter("username");

        if (username == null || "".equals(username) ) {
            resp.getWriter().write(false + "");
        }else {
            //1. 加载mybatis的核心配置文件，获取 SqlSessionFactory
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new
                    SqlSessionFactoryBuilder().build(inputStream);

            //获取sqlSessionFactory对象,用他来执行sql
            SqlSession sqlSession = sqlSessionFactory.openSession();

            //执行sql

            //获取Mapper接口的代理对象
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            User user = userMapper.findUserByUserName(username);

            //释放资源
            inputStream.close();

            if (user == null) {
                resp.getWriter().write(true + "");
            }else {
                resp.getWriter().write(false + "");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                                                throws ServletException, IOException {

    }
}
